package rs.networx.dao;

import java.util.List;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.Query;
import rs.networx.entity.Nottification;
import rs.networx.entity.Person;

@Stateless
@Local(NottificationDao.class) 
public class NottificationDaoBean extends GenericDaoBean<Nottification, Integer> implements NottificationDao {

	
	@Override
	public List<Nottification> getNonViewedUserNottifications(Integer personID,
			Integer filter) {
		System.out.println("Getting non viewed user nottifications ...");
		Query q = em.createQuery("SELECT DISTINCT n FROM Nottification n, Person p " +
				"WHERE p.id=:id AND n.owner.id=p.id AND type=:type");
		
		q.setParameter("id", personID);
		q.setParameter("type", filter);
		
		@SuppressWarnings("unchecked")
		List<Nottification> nottifications = q.getResultList();
		System.out.println("loaded " +nottifications.size()+ "notifications");

		return nottifications;
	}

	@Override
	public List<Nottification> getNonViewedUserNottifications(Integer personID) {
		System.out.println("Getting non viewed user nottifications ...");
		Query q = em.createQuery("SELECT DISTINCT n FROM Nottification n, Person p " +
				"WHERE p.id=:id AND n.owner.id=p.id AND type=:type");
		
		q.setParameter("id", personID);
		
		@SuppressWarnings("unchecked")
		List<Nottification> nottifications = q.getResultList();
		System.out.println("loaded " +nottifications.size()+ "notifications");

		return nottifications;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Integer getNottificationsCountForLoggedUser(Person loggedUser) {
		
		System.out.println("Loaded getNottificationsCountForLoggedUser...");
		
		Query q = em.createQuery("SELECT nott FROM Nottification nott WHERE nott.owner=:loggedUser and nott.viewed=0");
		
		q.setParameter("loggedUser", loggedUser);
		List<Nottification> results = q.getResultList();

		if (results.size() == 0) {
			return new Integer(0);
		}
		System.out.println("Loaded: " + results.size() + " nottifications");
		return new Integer(results.size());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Nottification> getNonViewedNottForUser(Integer intLoggedUserID) {
		// TODO Auto-generated method stub
		
		System.out.println("Loaded getNonViewedNottForUser...");
		
		// EAGER fetching nottifications...
		Query q = em.createQuery("SELECT DISTINCT n FROM Nottification n, Person p " +
				"WHERE p.id=:id AND n.owner.id=p.id AND n.viewed=0");
		
		q.setParameter("id", intLoggedUserID);
		List<Nottification> nottifications = q.getResultList();	    

		System.out.println("Loaded: " + nottifications.size() + " nottifications");
		return nottifications;
	}
}
